//table显示ID
var tableDiv="tablepythonVODiv";
//详情对话框
var detailDiv="detailpythonVODiv";
//表单DIV
var formDiv = "addpythonVOForm";
//添加对话框
var addDlgDiv ="addpythonVODiv";
//添加按钮
var addBtn = "pythonVOAddBtn";
//新增按钮  
var addDlgVO = "addPythonVO";
//模糊搜索ID
var searchDiv= "searchpythonVOForm";

//对象查询地址
var queryUrl="../system/pythonVO/queryPythonVOPageList";
//对象增加地址
var addUrl="../system/pythonVO/savePythonVO"
//对象修改地址
var updateUrl="../system/pythonVO/updatePythonVOById"
//对象删除地址
var deleteUrl="../system/pythonVO/deletePythonVOById"
//对象详情地址
var detailUrl="../system/pythonVO/queryPythonVOById"
//图片显示路径
var ftp = "http://172.16.1.52:3001/"
var getAllPythonTypeData;//所有的系统脚本类型
$(function(){
	getPythonType();
	getChangPythonType("pythonTypeSearch",null);
	//初始化时间插件
	$(".ui_timepicke").datepicker({
		  language:'zh-CN',
		  CustomFormat: "yyyy-mm-dd",
	      minView: "month", 
	      changeYear: true,
	      yearRange: "-200:+0",
	      timepicker:false,    
	      todayBtn: true,
	      autoclose:true
	});
	
	//显示系统脚本某行的详情
	$("#"+tableDiv+" tbody").on("click","#detailDataBtn",function(){
		var pk=$(this).attr("data-id");
		$.post(detailUrl,{pythonId:pk},function(data){
			showDetailData(data);
		});
	});
	
	//显示详情对话框
	function showDetailData(data){
		for(var k in data){
			var ele =$("#"+detailDiv+" #"+k+"Detail");
			if(k=="pythonType"){
				getChangPythonType("pythonType",data[k]);
				for(var i=0;i<getAllPythonTypeData["103"].length;i++){
					if(data[k] == getAllPythonTypeData["103"][i]["dictId"]){
						ele.html(getAllPythonTypeData["103"][i]["dictVal"]);
					}
				}
			}else{
				ele.html(data[k]);
			}
		}
		$("#"+detailDiv).modal("show");
	};
	
	//删除
	$("#"+tableDiv+" tbody").on("click","#deleteDataBtn",function(){
		var pk=$(this).attr("data-id");
		confirm("您确定要删除此条信息吗 ?", function(isConfirm){
			if(isConfirm){
				$.post(deleteUrl,{pythonId:pk},function(data){
					if(data !=null && typeof(data)!="undefined"){
						if(data.flg==true){
							swal("成功","操作成功","success");
						}else if(data.flg==false){
							swal("失败","操作失败","error");
						}
					}
					reloadData();
				});
				
			}else{
				swal("取消","您的操作已取消","error");
			}
		});
	});
	
	var tabForm = $('#' + formDiv);
    var errorForm = $('.alert-error', tabForm);
    var successForm = $('.alert-success', tabForm);
	//初始化表单-新增和删除
	function initFormValidate(param){
		var url="";
		if(param=="add"){
			url=addUrl;
		}else if(param=="update"){
			url=updateUrl;
		}
		$("#"+formDiv).attr("action",url);
		
		//表单验证(新)
		$("#"+formDiv).validate({
	        errorElement: 'span', //default input error message container
	        errorClass: 'help-inline', // default input error message class
	        focusInvalid: false, // do not focus the last invalid input
	        ignore: "",
	        rules: {
	        		pythonProject:{required:true,checkName:true}, 
	        		pythonType:{required:true,}, 
	        		pythonParam:{required:true,}, 
	        		pythonCode:{required:true,}
	        },
	        invalidHandler: function (event, validator) { //display error alert on form submit              
	            successForm.hide();
	            errorForm.show();
	            App.scrollTo(errorForm, -200);
	        },
	        highlight: function (element) { // hightlight error inputs
	            $(element).closest('.help-inline').removeClass('ok'); // display OK icon
	            $(element).closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
	        },
	        unhighlight: function (element) { // revert the change dony by hightlight
	            $(element).closest('.control-group').removeClass('error'); // set error class to the control group
	        },
	        success: function (label) {
	            label.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
	            label.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
	        },
	        messages:{teacherName:{pattern:'必须是汉字'}},
	        submitHandler: function (form) {
	            successForm.show();
	            errorForm.hide();
	            valditFlag = true;//防止重复录入
	            //文件上传成功后，向后台插入数据
	            tabForm.ajaxSubmit({
					type:"post",
					url:tabForm.attr("action"),
					success:function(data){
						if(data.flg==true){
							swal("成功","操作成功", "success");
							$("#"+addDlgDiv).modal("hide");
							reloadData();
						}else if(data.flg==false){
							swal("失败","操作失败","error");
							$("#"+addDlgDiv).modal("hide");
							reloadData();
						}
						
					}
				});
	            return false;
	        }
   		});
   		
	}
	
	
	//新增按钮
	$("#"+addDlgVO).bind("click",function(){
		reset();
		$("#"+addBtn).text("保存");
		$("#" + formDiv+ " #"+addBtn).attr("disabled",false);
		valditFlag =false;
		$("#"+ addDlgDiv).modal("show");
		getChangPythonType("pythonType",null)
		
		initFormValidate("add");
	});
	
	//新增数据保存按钮
	
	$("#"+addBtn).on("click",function(){
		if(valditFlag){
			return;
		}
		$('#' + formDiv).submit();
		resetRequired();
		reloadData();
	});
	
	//修改
	$("#"+tableDiv+" tbody").on("click","#updateDataBtn",function(){
		
		var pk=$(this).attr("data-id");
		$("."+formDiv+"_checktip").html(""); 
		reset();
		$("#"+addBtn).text("修改");
		$.ajax({url:detailUrl,data:{pythonId:pk},type:"post",async:false,success:function(data){
			if(data !=null && typeof(data)!="undefined"){
				for(var k in data){
					var ele =$("#"+formDiv+" #"+k);
					
					if(k=="pythonType"){
						getChangPythonType("pythonType",data[k]);
					}else if(k=="pythonProject"){
						$("#checkProjectName").val(data[k]);
						ele.val(data[k]);
					}else{
						ele.val(data[k]);
					}
					
				}
				valditFlag = false;
				$("#"+ addDlgDiv).modal("show");
				initFormValidate("update");
			}
		}
		});
		initFormValidate("update");
	});
	
	//初始化表单
	function reset(){
		$("#"+formDiv).find("input").val("");
		$(".help-inline").closest('.control-group').removeClass('ok');
   		$(".help-inline").closest('.control-group').removeClass('error');
   		$(".help-inline").closest('.control-group').removeClass('success');
   		$(".help-inline").removeClass('ok');
   	    $(".help-inline").html('');
   	    $("br[name='br']").remove();
   	    $(".alert-success").attr("display","none");
   	    $(".alert-error").attr("display","none");
   	    $(".alert-error").attr("style","");
   	    $(".alert-success").attr("style","");
   	    $("#checkProjectName").val("");
   	    $("#pythonCode").val("");
   	    //$('#' + formDiv).reset();
	}
	
	//修改验证样式
	function resetRequired(){
	}
	
	
	//验证系统脚本名称是否重复
	$.validator.addMethod("checkName",function(value,element){
		return checkProjectName($("#pythonProject").val(),$("#checkProjectName").val());
    },"<font style='color:#E47068 !important'>系统脚本名称重复，请重新输入</font>");
	
	function checkProjectName(s,n){
		var judge = false;
		$.ajax({
			url: "../system/pythonVO/queryAllPythonVOIdAndName?str="+s,
			async: false,
			success : function(data){
				if(s==n){
					judge = true;
				}else{
					if(data.length==0){
						judge = true;
					}
				}
			}
		});
		return judge;
	}
	
	//获取所有的系统脚本类型
	function getPythonType(){
		$.ajax({
			url: "../proDict/queryDictByCodes?codes="+103,
			async: false,
			success : function(data){
				getAllPythonTypeData = data;
			}
		});
	}
	
	
});//-------------预加载结束

//select框通用方法
function getChangPythonType(id,selectid){
	var strProjectName="<option value=''></option>";
	for(var i=0;i<getAllPythonTypeData["103"].length;i++){
		strProjectName += "<option ";
		if(selectid ==getAllPythonTypeData["103"][i]["dictId"]){
			strProjectName += " selected=selected ";
		}
		strProjectName+=" value="+getAllPythonTypeData["103"][i]["dictId"]+">"+getAllPythonTypeData["103"][i]["dictVal"]+"</option>";
	}
	$("#"+id).empty();
	$("#"+id).append(strProjectName);
	$("#"+id).selectpicker('render');
	$("#"+id).selectpicker('refresh');
	$("#"+id).parent().css("width","100%");
}


function showProjectTypeName(full){
	var str="";
	for(var i=0;i<getAllPythonTypeData["103"].length;i++){
		if(full.pythonType == getAllPythonTypeData["103"][i]["dictId"]){
			str+=getAllPythonTypeData["103"][i]["dictVal"];
		}
	}
	return str;
}